package com.xuan.contest.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xuan.contest.common.job.ExecuteJob;
import com.xuan.contest.common.tips.ErrorTip;
import com.xuan.contest.common.tips.SuccessTip;
import com.xuan.contest.common.tips.Tip;
import com.xuan.contest.common.utils.ContestStatusEnum;
import com.xuan.contest.entry.ContestEntity;
import com.xuan.contest.entry.UserAnswerEntity;
import com.xuan.contest.service.IConTestService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Queue;

/**
 * @author XinZhaoXuan
 * @date 2018/9/7
 */
@RestController
@RequestMapping("contest")
public class AnswerController {


    private static final Logger LOGGER = LoggerFactory.getLogger(AnswerController.class);


    @Autowired
    private IConTestService conTestService;
    @Autowired
    private ExecuteJob job;

    @RequestMapping("index")
    public Tip index(Integer userId, Integer problemId, Integer answer, Integer contestId) {
        Calendar calendar = Calendar.getInstance();

        ContestEntity contestEntity = conTestService.selectOne(new EntityWrapper<ContestEntity>().eq("id", contestId));

        if (contestEntity == null) {
            return new ErrorTip(501, "系统错误");
        }

        if (contestEntity.getStatus().equals(ContestStatusEnum.NOT_RUNING.getValue())) {
            return new ErrorTip(501, "该活动未开启");
        }


        if (calendar.getTime().compareTo(contestEntity.getStartTime()) < 0) {
            return new ErrorTip(501, "活动暂未开始");
        }

        if (calendar.getTime().compareTo(contestEntity.getEndTime()) > 0) {
            return new ErrorTip(501, "活动已经结束");
        }

        UserAnswerEntity userAnswerEntity = new UserAnswerEntity();
        userAnswerEntity.setUserId(userId);
        userAnswerEntity.setAnswer(answer);
        userAnswerEntity.setProblemId(problemId);
        userAnswerEntity.setContestId(contestId);

        conTestService.answer(userAnswerEntity);

        return new SuccessTip();
    }

    @RequestMapping("start")
    public Tip startContest(Integer contestId) {
        Tip tip = new SuccessTip();

        try {
            conTestService.approvalContest(contestId);
        } catch (Exception e) {
            tip = new ErrorTip(501, e.getMessage());
        }

        return tip;
    }

}
